<template>
  <view class="product-list-page">
    <!-- 页面加载状态 -->
    <PageLoading :show="pageLoading" :primary-color="primaryColor" loading-text="加载中..." />
    
    <!-- 页面主要内容 -->
    <view class="page-content" v-show="shouldShowContent">
    <view class="header">
      <text class="title">商品列表</text>
      <view class="cache-info" @click="showCacheStatus">
        <text class="cache-text">缓存状态</text>
      </view>
    </view>
    
    <view class="main-content">
      <!-- 左侧分类导航 -->
      <view class="category-sidebar">
        <view class="category-header">
          <text class="category-title">分类</text>
        </view>
        <scroll-view scroll-y class="category-scroll">
          <!-- 全部分类 -->
          <view 
            class="category-item" 
            :class="{active: currentCategoryId === 'all'}"
            @click="selectCategory('all', '全部')"
          >
            <text class="category-text">全部</text>
          </view>
          
          <!-- 父级分类 -->
          <view v-for="parentCategory in categories" :key="parentCategory.categoryId">
            <view 
              class="category-item parent-category" 
              :class="{active: currentCategoryId === parentCategory.categoryId, expanded: parentCategory.expanded}"
            >
              <view class="category-content" @click="selectCategory(parentCategory.categoryId, parentCategory.categoryName)">
                <text class="category-text">{{ parentCategory.categoryName }}</text>
              </view>
              <text class="expand-icon" v-if="parentCategory.children && parentCategory.children.length > 0"
                    @click.stop="toggleParentCategory(parentCategory)">
                {{ parentCategory.expanded ? '▼' : '▶' }}
              </text>
            </view>
            
            <!-- 子级分类 -->
            <view v-if="parentCategory.expanded && parentCategory.children" class="child-categories">
              <view 
                v-for="childCategory in parentCategory.children" 
                :key="childCategory.categoryId"
                class="category-item child-category" 
                :class="{active: currentCategoryId === childCategory.categoryId}"
                @click="selectCategory(childCategory.categoryId, childCategory.categoryName)"
              >
                <text class="category-text">{{ childCategory.categoryName }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 右侧商品列表 -->
      <view class="product-content">
        <view class="filter-tabs">
          <view 
            class="tab-item" 
            :class="{ active: activeTab === 'all' }"
            @click="switchTab('all')"
          >
            全部商品
          </view>
          <view 
            class="tab-item" 
            :class="{ active: activeTab === 'hot' }"
            @click="switchTab('hot')"
          >
            热销商品
          </view>
          <view 
            class="tab-item" 
            :class="{ active: activeTab === 'recommend' }"
            @click="switchTab('recommend')"
          >
            推荐商品
          </view>
        </view>
        
        <scroll-view scroll-y class="product-scroll">
          <view class="product-grid">
            <view 
              class="product-item" 
              v-for="product in currentProducts" 
              :key="product.id"
              @click="goToDetail(product.id)"
            >
              <image class="product-image" :src="product.image" mode="aspectFill"></image>
              <view class="product-info">
                <text class="product-name">{{ product.name || product.title }}</text>
                <view class="price-row">
                  <text class="price">¥{{ product.price }}</text>
                  <text class="sales" v-if="product.sales">销量{{ product.sales }}</text>
                </view>
              </view>
            </view>
          </view>
          
          <view class="loading" v-if="loading">
            <text>加载中...</text>
          </view>
          
          <view class="empty" v-if="!loading && currentProducts.length === 0">
            <text>暂无商品数据</text>
            <button class="refresh-btn" @click="refreshData">刷新数据</button>
          </view>
        </scroll-view>
      </view>
    </view>
    </view>
  </view>
</template>

<script>
import { listProduct, listMobileHotProduct, listMobileRecommendProduct } from '@/api/product.js'
import productCache from '@/utils/productCache.js'
import { API_CONFIG } from '@/api/config.js'
import { getThemeColorFromGlobal, getThemePrimaryColor } from '@/utils/themeUtils'
import PageLoading from '@/components/PageLoading/index.vue'
import pageLoadingMixin from '@/mixins/pageLoading.js'

export default {
  components: {
    PageLoading
  },
  mixins: [pageLoadingMixin],
  data() {
    return {
      activeTab: 'all',
      loading: false,
      allProducts: [],
      hotProducts: [],
      recommendProducts: [],
      cacheStatus: {
        all: false,
        hot: false,
        recommend: false
      },
      categories: [],
      currentCategoryId: 'all',
      currentCategoryName: '全部',
      themeColor: '1' // 主题色
    }
  },
  
  computed: {
    currentProducts() {
      switch (this.activeTab) {
        case 'hot':
          return this.hotProducts
        case 'recommend':
          return this.recommendProducts
        default:
          return this.allProducts
      }
    },
    // 动态主题色
    primaryColor() {
      return getThemePrimaryColor(this.themeColor || '1')
    }
  },
  
  async onLoad() {
    // 开始页面加载
    this.startPageLoading()
    
    try {
      // 初始化主题色
      await this.initThemeColor()
      this.markThemeLoaded()
      
      // 加载初始数据
      await this.loadInitialData()
      
      // 标记数据已加载
      this.markDataLoaded()
    } catch (error) {
      // console.error('商品列表页面加载失败:', error)
      this.forceCompletePageLoading()
    }
  },
  
  methods: {
    // 加载初始数据
    async loadInitialData() {
      // 加载分类数据
      await this.loadCategories()
      
      // 优先从缓存加载数据
      this.loadFromCache()
      
      // 如果缓存中没有数据，则从API加载
      if (this.allProducts.length === 0) {
        await this.loadAllProducts()
      }
      if (this.hotProducts.length === 0) {
        await this.loadHotProducts()
      }
      if (this.recommendProducts.length === 0) {
        await this.loadRecommendProducts()
      }
    },
    
    // 加载分类数据
      async loadCategories() {
        try {
          const { getCategoryTreeList } = require('@/api/category')
          const response = await getCategoryTreeList({
            status: '0' // 0表示正常状态
          })
          // console.log('分类API响应:', response)
          if (response.code === 200) {
            this.categories = response.rows || response.data || []
            // 为每个父级分类添加展开状态
            this.categories.forEach(category => {
              this.$set(category, 'expanded', false)
            })
            // console.log('加载分类成功:', this.categories)
          } else {
            // console.error('分类API返回错误:', response)
          }
        } catch (error) {
          // console.error('加载分类失败:', error)
          uni.showToast({
            title: '分类加载失败',
            icon: 'none'
          })
        }
      },
    
    // 选择分类
    selectCategory(categoryId, categoryName) {
      this.currentCategoryId = categoryId
      this.currentCategoryName = categoryName
      // 根据分类筛选商品
      this.filterProductsByCategory()
    },
    
    // 切换父级分类展开状态
    toggleParentCategory(parentCategory) {
      this.$set(parentCategory, 'expanded', !parentCategory.expanded)
    },
    
    // 根据分类筛选商品
    filterProductsByCategory() {
      // 这里可以根据分类ID重新加载商品数据
      // 暂时保持现有逻辑，后续可以添加分类筛选功能
      // console.log('当前选中分类:', this.currentCategoryId, this.currentCategoryName)
    },
    
    // 从缓存加载数据
    loadFromCache() {
      const orgId = API_CONFIG.ORG_ID
        const cachedHot = productCache.getProductCache('hot', orgId)
        const cachedRecommend = productCache.getProductCache('recommend', orgId)
        const cachedAll = productCache.getProductCache('all', orgId)
      
      if (cachedHot) {
        this.hotProducts = cachedHot
        // console.log('从缓存加载热销商品:', cachedHot.length)
      }
      
      if (cachedRecommend) {
        this.recommendProducts = cachedRecommend
        // console.log('从缓存加载推荐商品:', cachedRecommend.length)
      }
      
      if (cachedAll) {
        this.allProducts = cachedAll
        // console.log('从缓存加载全部商品:', cachedAll.length)
      }
    },
    
    // 加载全部商品
    async loadAllProducts() {
      this.loading = true
      try {
        const response = await listProduct({
          pageNum: 1,
          pageSize: 50,
          publishStatus: '1',
          status: '0'
        })
        
        if (response.code === 200 && response.rows) {
          this.allProducts = this.processProductData(response.rows)
          const orgId = API_CONFIG.ORG_ID
        productCache.setProductCache('all', this.allProducts, orgId)
          // console.log('全部商品数据已加载并缓存:', this.allProducts.length)
        }
      } catch (error) {
        // console.error('加载全部商品失败:', error)
        uni.showToast({ title: '加载失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    },
    
    // 加载热销商品
    async loadHotProducts() {
      try {
        const response = await listMobileHotProduct({
          pageNum: 1,
          pageSize: 20
        })
        
        if (response.code === 200 && response.rows) {
          this.hotProducts = this.processProductData(response.rows)
          const orgId = API_CONFIG.ORG_ID
        productCache.setProductCache('hot', this.hotProducts, orgId)
          // console.log('热销商品数据已加载并缓存:', this.hotProducts.length)
        }
      } catch (error) {
        // console.error('加载热销商品失败:', error)
      }
    },
    
    // 加载推荐商品
    async loadRecommendProducts() {
      try {
        const response = await listMobileRecommendProduct({
          pageNum: 1,
          pageSize: 20
        })
        
        if (response.code === 200 && response.rows) {
          this.recommendProducts = this.processProductData(response.rows)
          const orgId = API_CONFIG.ORG_ID
        productCache.setProductCache('recommend', this.recommendProducts, orgId)
          // console.log('推荐商品数据已加载并缓存:', this.recommendProducts.length)
        }
      } catch (error) {
        // console.error('加载推荐商品失败:', error)
      }
    },
    
    // 处理商品数据
    processProductData(products) {
      return products.map(item => {
        // 直接使用图片URL，不需要拼接服务器地址（七牛云存储）
        let imageUrl = item.mainImage || 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=300&h=300&fit=crop'
        
        // 构建商品描述信息，避免使用富文本字段
        let descriptionParts = []
        if (item.keywords) {
          descriptionParts.push(item.keywords)
        }
        if (item.categoryName) {
          descriptionParts.push(`分类: ${item.categoryName}`)
        }
        if (item.brandName) {
          descriptionParts.push(`品牌: ${item.brandName}`)
        }
        const description = descriptionParts.length > 0 ? descriptionParts.join(' | ') : '精选商品'
        
        return {
          id: item.productId,
          name: item.productName || '商品名称',
          title: item.productName || '商品名称',
          description: description,
          image: imageUrl,
          price: item.price ? item.price.toString() : '0.00',
          sales: item.saleCount || 0,
          keywords: item.keywords || '',
          categoryName: item.categoryName || '',
          brandName: item.brandName || ''
        }
      })
    },
    
    // 切换标签
    switchTab(tab) {
      this.activeTab = tab
    },
    
    // 显示缓存状态
    showCacheStatus() {
      const status = productCache.getCacheStatus()
      let message = '缓存状态:\n'
      Object.keys(status).forEach(type => {
        const info = status[type]
        message += `${type}: ${info.valid ? '有效' : '无效'} (${info.count}条)\n`
        if (info.timestamp) {
          message += `更新时间: ${info.timestamp}\n`
        }
      })
      
      uni.showModal({
        title: '缓存状态',
        content: message,
        showCancel: true,
        cancelText: '关闭',
        confirmText: '清除缓存',
        success: (res) => {
          if (res.confirm) {
            this.clearCache()
          }
        }
      })
    },
    
    // 清除缓存
    clearCache() {
      productCache.clearAllProductCache()
      this.allProducts = []
      this.hotProducts = []
      this.recommendProducts = []
      uni.showToast({ title: '缓存已清除', icon: 'success' })
    },
    
    // 刷新数据
    async refreshData() {
      productCache.clearAllProductCache()
      this.allProducts = []
      this.hotProducts = []
      this.recommendProducts = []
      await this.loadInitialData()
      uni.showToast({ title: '数据已刷新', icon: 'success' })
    },
    
    // 跳转到商品详情
    goToDetail(productId) {
      // 提取原始商品ID，去除_dup_后缀
      const originalId = this.getOriginalProductId(productId)
      uni.navigateTo({
        url: `/pages/product/detail?id=${originalId}`
      })
    },
    
    // 获取原始商品ID，去除_dup_后缀
    getOriginalProductId(id) {
      if (!id) return 1
      // 如果ID包含_dup_，提取原始ID
      if (typeof id === 'string' && id.includes('_dup_')) {
        return id.split('_dup_')[0]
      }
      return id
    },
    
    // 初始化主题色
    async initThemeColor() {
      try {
        this.themeColor = await getThemeColorFromGlobal()
        // console.log('主题色已初始化:', this.themeColor)
      } catch (error) {
        // console.error('初始化主题色失败:', error)
        this.themeColor = '1' // 默认主题色
      }
    }
  }
}
</script>

<style scoped>
.product-list-page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.cache-info {
  padding: 10rpx 20rpx;
  background: #007aff;
  color: #fff;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.main-content {
  display: flex;
  height: calc(100vh - 200rpx);
  background: #fff;
  border-radius: 10rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

/* 左侧分类导航样式 */
.category-sidebar {
  width: 200rpx;
  background: #f8f9fa;
  border-right: 1rpx solid #eee;
  display: flex;
  flex-direction: column;
}

.category-header {
  padding: 12rpx 15rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  text-align: center;
}

.category-title {
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}

.category-scroll {
  flex: 1;
  height: 100%;
}

.category-item {
  padding: 12rpx 15rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.category-item.active {
  background: #007aff;
  color: #fff;
}

.category-item.parent-category {
  font-weight: 500;
}

.category-content {
  flex: 1;
}

.category-text {
  font-size: 26rpx;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.category-item.active .category-text {
  color: #fff;
}

.expand-icon {
  font-size: 20rpx;
  color: #999;
  margin-left: 10rpx;
}

.category-item.active .expand-icon {
  color: #fff;
}

.child-categories {
  background: #f5f5f5;
}

.child-category {
  padding: 10rpx 15rpx 10rpx 35rpx;
  background: #f5f5f5;
}

.child-category .category-text {
  font-size: 24rpx;
  color: #666;
}

.child-category.active {
  background: #007aff;
}

.child-category.active .category-text {
  color: #fff;
}

/* 右侧商品内容样式 */
.product-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.filter-tabs {
  display: flex;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  font-size: 28rpx;
  color: #666;
  background: #fff;
  border-right: 1rpx solid #eee;
}

.tab-item:last-child {
  border-right: none;
}

.tab-item.active {
  color: #007aff;
  background: #f0f8ff;
  font-weight: bold;
}

.product-scroll {
  flex: 1;
  height: 100%;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  padding: 20rpx;
}

.product-item {
  background: #fff;
  border-radius: 10rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.product-item:active {
  transform: scale(0.98);
}

.product-image {
  width: 100%;
  height: 300rpx;
  object-fit: cover;
}

.product-info {
  padding: 20rpx;
}

.product-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}



.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff4757;
}

.sales {
  font-size: 22rpx;
  color: #999;
}

.loading, .empty {
  text-align: center;
  padding: 60rpx 20rpx;
  color: #999;
  font-size: 28rpx;
}

.refresh-btn {
  margin-top: 20rpx;
  padding: 20rpx 40rpx;
  background: #007aff;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
}
</style>